package api

import (
	"context"
	"time"

	"dev.ixmxm.top/rms/codes"
	"dev.ixmxm.top/rms/utils/log"
)

// @Summary 获得授权用户信息
// @Description
// @Accept application/json
// @Produce application/json
// @Success 1 {object} usermanager.AuthorInfo "data数据:授权用户信息"
// @Tags 授权
// @Router /sys_user/get_author_user [get]
func (hg *HttpGateway) GetAuthorUser(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	res := hg.dispatcher.UM().GetAuthorInfo()
	return res, nil
}

// @Summary 获得授权用户开关状态
// @Description
// @Accept application/json
// @Produce application/json
// @Success 1 {object} usermanager.AuthorStatus "data数据:开关状态和时间"
// @Tags 授权
// @Router /sys_user/get_author_user_switch [get]
func (hg *HttpGateway) GetAuthorUserSwitch(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	res, err := hg.dispatcher.UM().QueryDatabase(ctx, hg.dispatcher.UM().Userauthor.TableNameSwitch())
	if res.IsNullFlag {
		res = nil
	}

	if err != nil {
		log.ErrorfWithContext(ctx, "get author users switch error:%s", err.UnWrapError())
		return nil, err
	}
	return res, nil
}

// @Summary 用户超时管理
// @Description
// @Accept application/json
// @Produce application/json
// @Success 1 {object} usermanager.AuthorStatus "data数据:超时状态和时间"
// @Tags 授权
// @Router /sys_user/get_author_user_timeout [get]
func (hg *HttpGateway) GetAuthorUserTimeOut(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	res, err := hg.dispatcher.UM().QueryDatabase(ctx, hg.dispatcher.UM().Userauthor.TableNameFail())
	if err != nil {
		log.ErrorfWithContext(ctx, "get author user time error:%s", err.UnWrapError())
		return nil, err
	}
	return res, nil
}

// @Summary 操作授权用户
// @Description
// @Accept application/json
// @Produce application/json
// @Param body body SaveUserAuthorSwitch true "操作授权用户"
// @Success 0 {object} ResponseExample "返回数据格式"
// @Tags 授权
// @Router /sys_user/operate_author_user_switch [post]
func (hg *HttpGateway) OperateAuthorUserSwitch(ctx context.Context, params interface{}) (interface{}, codes.Code) {
	p := params.(*SaveUserAuthorSwitch)
	if p.Status == 2 {
		hg.dispatcher.UM().ClearDB(ctx, hg.dispatcher.UM().Userauthor.TableNameFail())
	}
	hg.dispatcher.UM().ClearDB(ctx, hg.dispatcher.UM().Userauthor.TableNameSwitch())
	//更新缓存
	hg.dispatcher.UM().InitCache(ctx)
	//将前端确认的Lock或UnLock写入数据库
	err := hg.dispatcher.UM().AddLabelToDB(ctx, p.Status, hg.dispatcher.UM().Userauthor.TableNameSwitch(), time.Now())
	if err != nil {
		log.ErrorfWithContext(ctx, "add lable to switchdb:%s", err.UnWrapError())
		return nil, err
	}
	return nil, nil
}
